﻿using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WebApplicationFileSys.Models;
using static System.Collections.Specialized.BitVector32;

namespace WebApplicationFileSys.Filter
{
    /// <summary>
    /// 登录过滤器
    /// </summary>
    public class LoginFilter : AuthorizeAttribute
    {
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            //filterContext.HttpContext.Session.Remove(KeyValueConfig.KeyUserSession);
            var user = filterContext.HttpContext.Session[KeyValueConfig.KeyUserSession];
            var token = filterContext.HttpContext.Request.Cookies[KeyValueConfig.Cookie_Token]?.Value;
           
            if (user == null && !IsValidToken(token))
            {

                filterContext.Result = new RedirectResult("/LoginHandle/LoginView");
                return;


            }



            //核心资源，需要管理员权限访问
            if (!string.IsNullOrWhiteSpace(Roles) && !LoginMode.admin)
            {

                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = new RedirectResult("/home/p403");
                return;

            }

        }

        private bool IsValidToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            SecurityToken validatedToken;
            try
            {
                // 验证JWT的有效性
                tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
            }
            catch (Exception)
            {
                return false;
            }

            var jwt = tokenHandler.ReadJwtToken(token);
            var tokenName = jwt.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Name && claim.Value.Equals(LoginMode.username));
            if (tokenName != null && validatedToken.ValidTo >= DateTime.UtcNow)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,

                ValidIssuer = KeyValueConfig.issuer,
                ValidAudience = KeyValueConfig.audience,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(KeyValueConfig.TokeKey))
            };
        }
    }
}